package com.nbicc.spring;

import com.nbicc.common.ResponseObj;
import com.nbicc.parent.async.AsyncTask;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.web.context.request.async.DeferredResult;
import java.util.concurrent.ExecutorService;

/**
 * @Author: lilingyan
 */
@Component
public class TaskExecutorServiceHolder {

    @Autowired
    private ExecutorService taskExecutorService;
    @Autowired
    private DataSourceTransactionManager txManager;

    public void submit(AsyncTask task, DeferredResult<Object> result){
        Runnable t = () ->{
            DefaultTransactionDefinition def = new DefaultTransactionDefinition();
            def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);// 事物隔离级别，开启事务
            TransactionStatus status = txManager.getTransaction(def); // 获得事务状态
            try {
                task.run();
                txManager.commit(status);
            } catch (Exception e) {
                e.printStackTrace();
                txManager.rollback(status);
                result.setErrorResult(e);
            }
        };

        result.onTimeout(()->{
            result.setErrorResult(ResponseObj.fail().setMessage("超时"));
        });

        taskExecutorService.submit(t);
    }

}
